﻿using System.Diagnostics;
using System.Net;
using System.Net.Sockets;

namespace FileSynchronizationClient.Common
{
    /// <summary>
    /// 公共方法
    /// </summary>
    public static class CommonHelper
    {
        /// <summary>
        /// 执行CMD
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        public static async Task<string> RunCmd(string cmd)
        {
            Console.WriteLine();
            string output = string.Empty;
            using (Process process = new Process())
            {
                process.StartInfo.FileName = "cmd.exe";
                process.StartInfo.UseShellExecute = false;        //是否使用操作系统shell启动
                process.StartInfo.RedirectStandardInput = true;   //接受来自调用程序的输入信息
                process.StartInfo.RedirectStandardOutput = true;  //由调用程序获取输出信息
                process.StartInfo.RedirectStandardError = true;   //重定向标准错误输出
                process.StartInfo.CreateNoWindow = true;          //不显示程序窗口
                process.StartInfo.Arguments = $@"/c {cmd}";       //CMD命令

                process.OutputDataReceived += (sender, e) =>
                {
                    if (!string.IsNullOrEmpty(e.Data))
                    {
                        Console.WriteLine(e.Data);
                        output += $"Normal: {e.Data}\n";
                    }
                };

                process.ErrorDataReceived += (sender, e) =>
                {
                    if (!string.IsNullOrEmpty(e.Data))
                    {
                        Console.WriteLine(e.Data);
                        output += $"Error:  {e.Data}\n";
                    }
                };

                process.Start();//启动程序

                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                await process.WaitForExitAsync();

                process.Close();

                Console.WriteLine();

                return output;
            }
        }

        /// <summary>
        /// 转圈加载
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public static void CircleLoading(string msg, Func<Task> action)
        {
            bool status = false;

            Task.Run(async () =>
            {
                try
                {
                    await action();
                }
                catch { throw; }
                finally { status = true; }
            });

            int animationIndex = 0;
            string[] animationFrames = { "|", "/", "-", "\\" };
            while (!status)
            {
                // 将光标移动到行首
                Console.Write("\r");

                // 显示旋转的进度指示器
                Console.Write("{0} {1}", msg, animationFrames[animationIndex]);

                // 增加动画帧索引
                animationIndex = (animationIndex + 1) % animationFrames.Length;

                Thread.Sleep(100); // 模拟操作延迟
            }
            Console.WriteLine();
        }

        /// <summary>
        /// 进度条加载
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="totalProgress"></param>
        /// <param name="func"></param>
        public static void Progress(string msg, int totalProgress, Func<ProgressSetting, Task> func)
        {
            ProgressSetting progress = new ProgressSetting();
            progress.totalProgress = totalProgress;

            Task.Run(async () =>
            {
                try
                {
                    await func(progress);
                }
                catch { throw; }
            });

            // 计算进度条百分比
            int progressPercentage = (int)((double)progress.currentProgress / progress.totalProgress * 100);

            while (progressPercentage != 100)
            {
                int totalCount = 30;
                double onePercentage = 100d / totalCount;

                progressPercentage = (int)((double)progress.currentProgress / progress.totalProgress * 100);

                //当前#个数
                int nowPercentCount = (int)Math.Floor(progressPercentage / onePercentage);

                Console.Write("\r"); // 将光标移动到行首
                                     // 绘制进度条
                Console.Write($"{msg} ");
                Console.Write(new string('▋', nowPercentCount));
                Console.Write(new string(' ', totalCount - nowPercentCount));
                Console.Write(" {0}%", progressPercentage);
                Thread.Sleep(100); // 模拟操作延迟
            }
        }

        /// <summary>
        /// 获取本机IP
        /// </summary>
        /// <returns></returns>
        public static string GetLocalIPAddress()
        {
            // 获取本地计算机的主机名
            string hostName = Dns.GetHostName();

            // 根据主机名解析 IP 地址
            IPHostEntry hostEntry = Dns.GetHostEntry(hostName);

            // 查找第一个非回环地址的 IPv4 地址
            foreach (IPAddress ipAddress in hostEntry.AddressList)
            {
                if (ipAddress.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(ipAddress))
                {
                    return ipAddress.ToString();
                }
            }

            return "IP Address not found";
        }
    }

    public class ProgressSetting
    {
        public int totalProgress { get; set; } = 10;

        public int currentProgress { get; set; } = 0;
    }
}
